<?php

namespace App\Models\Traits;

use Illuminate\Database\Eloquent\Builder;

trait HasEasyStatus
{
    /**
     * Notes   : 对使用该trait的模型进行初始化，设置状态字段类型
     *
     * @Date   : 2023/11/6 15:14
     * @Author : <Jason.C>
     */
    public function initializeHasEasyStatus(): void
    {
        if (!isset($this->casts[$this->getStatusField()])) {
            $this->casts[$this->getStatusField()] = 'bool';
        }
    }

    protected function getStatusField(): string
    {
        if (property_exists($this, 'statusField')) {
            return $this->statusField;
        }

        return 'status';
    }

    public function scopeOfEnabled(Builder $query): Builder
    {
        return $query->where($this->getStatusField(), true);
    }

    public function scopeOfDisabled(Builder $query): Builder
    {
        return $query->where($this->getStatusField(), false);
    }

    public function enable(): bool
    {
        $this->{$this->getStatusField()} = true;

        return $this->save();
    }

    public function disable(): bool
    {
        $this->{$this->getStatusField()} = false;

        return $this->save();
    }

    public function isEnabled(): bool
    {
        return $this->{$this->getStatusField()};
    }

    public function isDisabled(): bool
    {
        return !$this->{$this->getStatusField()};
    }
}
